<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./js/axios.min.js"></script>
    <script src="./js/api.js"></script>
  </head>
  <body>
    <h1>修改</h1>

    <div id="update-div">
      <input type="text" name="" id="" />
      <input type="text" name="" id="" />
      <input type="text" name="" id="" />
      <input type="text" name="" id="" />
      <input type="button" name="" id="" value="保存" onclick="saveFn()" />
    </div>
    <script>
      /**  
         * 
         修改功能    在商品列表生成的时候 

         <a href="update.html?pid=${pObj.pid}">修改</a>

         点击修改按钮-跳转到 修改页面，通过url 传递过去了 商品的id  ？pid=111  

         在修改页面 获取 url  搜索字段    pid   
         
         调用 根据商品id 获取商品详情的接口 -》  展示到  input中   

         给保存按钮添加点击事件，点击的时候 获取输入框的值，发起 修改请求
         * 
         *  */

      //  ?pid=499854&aa=12
      console.log(location.search);

      //   URLSearchParams 构造函数 能?pid=499854&aa=12-》对象
      let obj = new URLSearchParams(location.search);
      console.log(obj.get("pid"));
      let pid = obj.get("pid");

      //   productDetailAPI
      //   接口参数：
      // id  商品的id
      axios
        .get(productDetailAPI, {
          params: { id: pid },
        })
        .then((res) => {
          let { data } = res;
          console.log(data);
          //商品详情数据
          let pObj = data.data;

          let ipts = document.querySelectorAll("#update-div input");
          ipts[0].value = pObj.pname;
          ipts[1].value = pObj.pprice;
          ipts[2].value = pObj.pimg;
          ipts[3].value = pObj.pdesc;
        });

      async function saveFn() {
        console.log("保存");
        let ipts = document.querySelectorAll("#update-div input");
        let pname = ipts[0].value;
        let pprice = ipts[1].value;
        let pimg = ipts[2].value;
        let pdesc = ipts[3].value;
        //pid
        let params = { pname, pprice, pimg, pdesc, pid };
        let { data } = await axios.get(productUpdateAPI, { params });
        console.log(data);
        alert(data.msg);
        location.href = "index.html";
      }
    </script>
  </body>
</html>
